package cn.kshost.zqyg.cart.service.impl;

import cn.kshost.zqyg.cart.service.CartService;
import cn.kshost.zqyg.client.product.ProductFeign;
import cn.kshost.zqyg.model.entity.h5.CartInfo;
import cn.kshost.zqyg.model.entity.product.ProductSku;
import cn.kshost.zqyg.model.vo.common.Result;
import cn.kshost.zqyg.utils.AuthContextUtil;
import com.alibaba.fastjson2.JSON;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private ProductFeign productFeign;

    @Override
    public void addToCart(String skuId, String skuNum) {

        Long userId = AuthContextUtil.getUserInfoValue().getId();
        //通过skuid获取商品信息
        Result<ProductSku> result = productFeign.getBySkuId(Long.parseLong(skuId.toString()));
        ProductSku productSku = result.getData();
        //通过redis拿到购物车数据 如果有数据基础上添加 如果没数据就直接添加
        String userKey = buildUserKey(userId);
        Object cartInfoObj = redisTemplate.opsForHash().get(userKey, skuId);
        CartInfo cartInfo = new CartInfo();
        if (null != cartInfoObj){
            cartInfo = JSON.parseObject(cartInfoObj.toString(), CartInfo.class);
            cartInfo.setSkuNum(cartInfo.getSkuNum()+Integer.valueOf(skuNum) );
            cartInfo.setIsChecked(1);
            cartInfo.setUpdateTime(new Date());
        }else{
            cartInfo.setUserId(userId);
            cartInfo.setSkuId(Long.valueOf(skuId));
            cartInfo.setCartPrice(productSku.getSalePrice());
            //设置个数
            cartInfo.setSkuNum(Integer.valueOf(skuNum));
            cartInfo.setImgUrl(productSku.getThumbImg());
            cartInfo.setSkuName(productSku.getSkuName());
            cartInfo.setIsChecked(1);
            cartInfo.setUpdateTime(new Date());
            cartInfo.setCreateTime(new Date());
        }

        redisTemplate.opsForHash().put(userKey,skuId,JSON.toJSONString(cartInfo) );
    }

    @Override
    public List<CartInfo> getCartList() {
        List<Object> cartInfoList = redisTemplate.opsForHash().values(buildUserKey(AuthContextUtil.getUserInfoValue().getId()));
        if (null != cartInfoList){
            List<CartInfo> collect = cartInfoList.stream().map(cartInfo -> JSON.parseObject(cartInfo.toString(), CartInfo.class)).sorted((o1, o2) -> o2.getCreateTime().compareTo(o1.getCreateTime())).collect(Collectors.toList());
            return collect;
        }
        return  new ArrayList<>();
    }

    @Override
    public void deleteCart(Long skuId) {
        redisTemplate.opsForHash().delete(buildUserKey(AuthContextUtil.getUserInfoValue().getId()),String.valueOf(skuId));
    }

    @Override
    public void clearCart() {
        redisTemplate.delete(buildUserKey(AuthContextUtil.getUserInfoValue().getId()));
    }

    @Override
    public void updateCheckCart(Long skuId, Integer isChecked) {

        String userKey = buildUserKey(AuthContextUtil.getUserInfoValue().getId());

        Boolean isExit = redisTemplate.opsForHash().hasKey(userKey, String.valueOf(skuId));
        if (isExit){
            Object CartInfoObj = redisTemplate.opsForHash().get(userKey, String.valueOf(skuId));
            CartInfo cartInfo = JSON.parseObject(CartInfoObj.toString(), CartInfo.class);
            cartInfo.setIsChecked(isChecked);
            redisTemplate.opsForHash().put(userKey,String.valueOf(skuId),JSON.toJSONString(cartInfo));
        }



    }

    @Override
    public void getAllCheckCart(Integer isChecked) {
        String userKey = buildUserKey(AuthContextUtil.getUserInfoValue().getId());
        List<Object> cartInfoObjList = redisTemplate.opsForHash().values(userKey);

         cartInfoObjList.stream().map(cartInfo ->
                {
                    CartInfo  newCartInfo=  JSON.parseObject(cartInfo.toString(), CartInfo.class);
                    newCartInfo.setIsChecked(isChecked);
                    return newCartInfo;
                }
                ).sorted((o1, o2) -> o2.getCreateTime().compareTo(o1.getCreateTime())).forEach(cartInfo ->{
             String cartInfoJson = JSON.toJSONString(cartInfo);
             redisTemplate.opsForHash().put(userKey,String.valueOf(cartInfo.getSkuId()),cartInfoJson);

         });




    }

    @Override
    public List<CartInfo> getAllChecked() {
        List<Object> orderInfoObj = redisTemplate.opsForHash().values(buildUserKey(AuthContextUtil.getUserInfoValue().getId()));

        if (orderInfoObj != null){
            List<CartInfo> cartInfoList = orderInfoObj.stream().map(orderInfo -> JSON.parseObject(orderInfo.toString(), CartInfo.class))
                    .filter(orderInfo -> orderInfo.getIsChecked() == 1)
                    .collect(Collectors.toList());

            return cartInfoList;
        }
        return new ArrayList<>();

    }

    private String buildUserKey(Long userId){

        return  "cart:user:"+userId;
   }
}
